package com.Test;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Files;
import java.util.Iterator;

/**
 * Description:
 * Copyright:   Copyright (c)2019
 * Company:     zefu
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2021-09-30 15:58:17
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2021-09-30     张李鑫                     1.0         1.0 Version
 */
public class Test01 {
    private int port = 6584;
    private Selector selector;
    private ByteBuffer fileBuffer;

    public Test01() throws Exception {
//		Path file = Path.of("ces.txt");
        File file = new File("/Users/user/Documents/MyGIt/zlx-study-home/src/main/java/com/Test/ces.md");
        byte[] data = Files.readAllBytes(file.toPath());
        fileBuffer = ByteBuffer.wrap(data);
        System.err.println(fileBuffer.position());
        selector = Selector.open();

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(port));
        serverSocketChannel.configureBlocking(false);

        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务启动成功");
    }


    public void service() {
        while (true) {
            SelectionKey key = null;
            try {
                selector.select();
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    key = (SelectionKey) iterator.next();
                    iterator.remove();
                    if (key.isAcceptable()) {
                        // "接受连接就绪事件"的响应代码
                        ServerSocketChannel serverSocketChannel =
                                (ServerSocketChannel) key.channel();
                        SocketChannel socketChannel = serverSocketChannel.accept();

                        socketChannel.configureBlocking(false);
                        SelectionKey selectionKey =
                                socketChannel.register(selector, SelectionKey.OP_WRITE);
                        selectionKey.attach(fileBuffer.duplicate());
                        System.out.println(socketChannel.getRemoteAddress());
                    }
                    if (key.isWritable()) {
                        // "写就绪事件"的响应代码
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        ByteBuffer bufferToSend = (ByteBuffer) key.attachment();
                        if (bufferToSend.hasRemaining()) {
                            System.out.println(bufferToSend.position());
                            socketChannel.write(bufferToSend);
                        } else {
                            socketChannel.close();
                            key.cancel();
                        }
                    }
                }
            } catch (IOException e) {
                try {
                    key.channel().close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                key.cancel();
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        new NonBlockingServer().service();
    }
}
